#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
统一混淆系统 - 主入口
整合了三个项目的所有功能，提供统一的流程编排和详细日志记录
"""

import os
import sys
import argparse
import logging
from datetime import datetime
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from core.utils_module.logger import setup_logger, ObfuscationLogger
from core.builtin_config_module.builtin_config_manager import BuiltInConfigManager
from core.utils_module.backup_manager import ProjectBackupManager
from core.cloners_module.project_cloner import ProjectCloner
from core.utils_module.file_utils import ensure_directory

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='统一混淆系统')
    parser.add_argument('--project-path', '-p', required=True, help='项目路径')
    parser.add_argument('--config', '-c', help='配置文件路径')
    parser.add_argument('--mode', '-m', choices=['swift', 'objc', 'mixed'], default='mixed', 
                       help='混淆模式: swift, objc, mixed')
    parser.add_argument('--action', '-a', choices=['obfuscate', 'restore', 'extract', 'inject', 'inject-dead-code', 'modify-images', 'restore-images', 'clean-backups', 'advanced-dummy', 'detailed-extract', 'analyze-usage', 'system-symbols', 'clone', 'backup', 'list-backups', 'incremental-backup', 'clean-old-backups'],
                       default='obfuscate', help='执行动作')
    parser.add_argument('--verbose', '-v', action='store_true', help='详细输出')
    parser.add_argument('--dry-run', action='store_true', help='模拟运行，不实际修改文件')
    parser.add_argument('--target-path', '-t', help='目标路径（用于克隆项目）')
    parser.add_argument('--bundle-id', help='新的iOS Bundle ID')
    parser.add_argument('--package-name', help='新的Android包名')
    parser.add_argument('--project-name', help='新的项目名称')
    parser.add_argument('--modify-fingerprints', action='store_true', default=True, help='修改文件指纹')
    parser.add_argument('--base-backup', help='基础备份路径（用于增量备份）')
    parser.add_argument('--keep-backups', type=int, default=5, help='保留的备份数量')
    # parser.add_argument('--use-legacy', action='store_true', help='使用旧的混淆系统')  # 已移除旧系统
    parser.add_argument('--obfuscation-level', choices=['basic', 'standard', 'advanced', 'maximum'],
                       default='standard', help='混淆级别（仅限unified模式）')
    parser.add_argument('--dead-code-complexity', choices=['low', 'medium', 'high', 'extreme'],
                       default='medium', help='死代码注入复杂度')
    parser.add_argument('--dead-code-probability', type=float, default=0.3,
                       help='死代码注入概率 (0.0-1.0)')
    parser.add_argument('--use-ast', action='store_true', default=True,
                       help='使用AST分析进行代码注入和提取')

    args = parser.parse_args()
    
    # 设置日志
    log_level = logging.DEBUG if args.verbose else logging.INFO
    base_logger = setup_logger('obfuscator', log_level)
    logger = ObfuscationLogger(base_logger)
    
    try:
        # 初始化新的统一配置系统
        config_manager = BuiltInConfigManager(args.config, logger)
        config = config_manager.get_config()
        
        # 应用命令行参数覆盖
        config.project_path = args.project_path
        config.mode = args.mode
        config.dry_run = args.dry_run
        config.logging.verbose = args.verbose
        
        # 验证配置
        config_errors = config.validate()
        if config_errors:
            logger.log_error("配置验证失败")
            for error in config_errors:
                logger.log_error(f"  - {error}")
            sys.exit(1)
        
        # 旧系统已移除，不再需要创建旧组件
        
        # 创建备份管理器和项目克隆器
        backup_manager = ProjectBackupManager(config, logger)
        project_cloner = ProjectCloner(config, logger)
        
        # 执行相应动作
        if args.action == 'obfuscate':
            # 检查是否使用新的统一系统（默认使用新系统，除非指定--use-legacy）
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                from core.interfaces_module.obfuscator import ObfuscationContext, ObfuscationLevel

                # 创建统一混淆器
                obfuscator = Obfuscator(config, logger)

                # 创建混淆上下文
                level_map = {
                    'basic': ObfuscationLevel.BASIC,
                    'standard': ObfuscationLevel.STANDARD,
                    'advanced': ObfuscationLevel.ADVANCED,
                    'maximum': ObfuscationLevel.MAXIMUM
                }

                context = ObfuscationContext(
                    project_path=args.project_path,
                    platform=config.platform if hasattr(config, 'platform') else 'unified',
                    languages=['swift', 'objc', 'java', 'kotlin'],
                    obfuscation_level=level_map[args.obfuscation_level]
                )

                # 执行混淆
                result = obfuscator.obfuscate(
                    project_path=args.project_path,
                    options={'use_cache': True, 'incremental': True}
                )

                if result.success:
                    logger.log_operation("混淆完成", f"处理 {result.files_processed} 个文件，混淆 {result.symbols_obfuscated} 个符号")
        elif args.action == 'restore':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                obfuscator.restore_project()
        elif args.action == 'extract':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                symbols = obfuscator.extract_symbols()
                logger.log_operation("符号提取完成", f"提取到 {len(symbols.get('classes', []))} 个类，{len(symbols.get('methods', []))} 个方法")
        elif args.action == 'inject':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                # 这里需要提供代码片段
                obfuscator.inject_code(use_ast=args.use_ast)
        elif args.action == 'inject-dead-code':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                result = obfuscator.inject_dead_code(
                    complexity=args.dead_code_complexity,
                    probability=args.dead_code_probability,
                    use_ast=args.use_ast
                )
                if result:
                    logger.log_operation("死代码注入", "成功注入死代码")
                else:
                    logger.log_error("死代码注入失败")
        elif args.action == 'modify-images':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                obfuscator.modify_image_md5()
        elif args.action == 'restore-images':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                obfuscator.restore_images()
        elif args.action == 'clean-backups':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                obfuscator.clean_image_backups()
        elif args.action == 'advanced-dummy':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                obfuscator.generate_advanced_dummy_code()
        elif args.action == 'detailed-extract':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                symbols = obfuscator.extract_detailed_symbols()
                output_path = os.path.join(config.output_dir, "detailed_symbols.json")
                obfuscator.generate_symbol_report(symbols, output_path)
        elif args.action == 'analyze-usage':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                symbols = obfuscator.extract_symbols()
                usage_stats = obfuscator.analyze_symbol_usage(symbols)
                output_path = os.path.join(config.output_dir, "usage_analysis.json")
                with open(output_path, 'w', encoding='utf-8') as f:
                    import json
                    json.dump(usage_stats, f, indent=2, ensure_ascii=False)
        elif args.action == 'system-symbols':
                logger.log_operation("系统选择", "使用新的统一混淆系统")
                from core.obfuscation_module.obfuscator import Obfuscator
                obfuscator = Obfuscator(config, logger)
                system_symbols = obfuscator.extract_system_symbols()
                output_path = os.path.join(config.output_dir, "system_symbols.json")
                with open(output_path, 'w', encoding='utf-8') as f:
                    import json
                    json.dump(system_symbols, f, indent=2, ensure_ascii=False)
        elif args.action == 'clone':
            if not args.target_path:
                logger.log_error("克隆项目需要指定目标路径 --target-path")
                sys.exit(1)
            project_cloner.clone_project(
                args.project_path,
                args.target_path,
                new_bundle_id=args.bundle_id,
                new_package_name=args.package_name,
                new_project_name=args.project_name,
                modify_fingerprints=args.modify_fingerprints
            )
        elif args.action == 'backup':
            backup_path = backup_manager.create_full_backup(args.project_path)
            logger.log_operation("备份完成", f"备份文件: {backup_path}")
        elif args.action == 'list-backups':
            backups = backup_manager.list_backups()
            logger.log_operation("备份列表", f"找到 {len(backups)} 个备份")
            for backup in backups:
                logger.log_operation(backup['filename'], 
                                   f"大小: {backup['size']/1024/1024:.2f}MB, 时间: {backup['modified']}")
        elif args.action == 'incremental-backup':
            if not args.base_backup:
                # 自动查找最新的完整备份
                backups = backup_manager.list_backups()
                full_backups = [b for b in backups if not b['filename'].startswith('incremental_')]
                if not full_backups:
                    logger.log_error("没有找到基础备份，请先创建完整备份")
                    sys.exit(1)
                args.base_backup = full_backups[0]['path']
            
            incremental_path = backup_manager.create_incremental_backup(args.project_path, args.base_backup)
            logger.log_operation("增量备份完成", f"备份文件: {incremental_path}")
        elif args.action == 'clean-old-backups':
            backup_manager.clean_old_backups(args.keep_backups)
            
    except Exception as e:
        logger.log_error(f"执行失败: {str(e)}")
        sys.exit(1)

if __name__ == '__main__':
    main()
